package com.san.common.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.san.common.auth.constant.ConstConfig;
import com.san.common.auth.dto.AuthToken;
import com.san.common.auth.dto.UserInfo;
import com.san.common.auth.exception.ForbiddenException;
import com.san.common.auth.service.AdminService;
import com.san.common.auth.util.RandomUtils;
import com.san.common.auth.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Resource
    RedisUtils redisUtils;

    @Override
    public String generateCode(String username) {
        String code = RandomUtils.authCode(ConstConfig.AUTH_CODE_LENGTH);
        UserInfo info = new UserInfo();
        info.setUserName(username);
        String infoStr = JSON.toJSONString(info);
        String key = ConstConfig.USER_PREFIX + ":" + code;
        Long cacheTime = ConstConfig.AUTH_CODE_CACHE_TIME;
        redisUtils.set(key, infoStr, cacheTime, TimeUnit.SECONDS);
        return code;
    }

    @Override
    public AuthToken getToken(String code, String userAccount) {
        String json = (String) redisUtils.get(ConstConfig.USER_PREFIX + ":" + code);
        if (StringUtils.isBlank(json)) {
            throw new ForbiddenException("code不存在或已失效");
        }
        UserInfo userInfo = JSONObject.parseObject(json, UserInfo.class);
        if (!userInfo.getUserName().equals(userAccount)) {
            throw new ForbiddenException("code与当前用户不匹配");
        }
        redisUtils.del(ConstConfig.USER_PREFIX + ":" + code);
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken(RandomUtils.randomUUIDWithoutDash());
        return authToken;
    }
}
